package com.utils;

import com.model.JobInfo;
import com.utils.pojo.LngLat;
import lombok.extern.java.Log;
import org.assertj.core.util.Strings;
import org.springframework.web.client.RestTemplate;

/**
 * 高德地图工具
 */
@Log
public class GaodeUtils {
    private static final String KEY = "91325d512744aef2727a3ee438570ada";
    private static final String CITY = "广州";
    /**
     * 获取经纬度
     * @param address
     * @return LngLat
     */
    public static LngLat getLagLat(String address) {
        RestTemplate restTemplate = new RestTemplate();
        GaodeAddrResponse response = restTemplate.getForEntity(getUrl(address), GaodeAddrResponse.class).getBody();
        if(response.getGeocodes() == null || response.getGeocodes().size() == 0) return null;
        String location = response.getGeocodes().get(0).getLocation();
        String[] locations = location.split(",");

        return new LngLat().setLng(Double.parseDouble(locations[0])).setLat(Double.parseDouble(locations[1]));
    }

    public static void setJobInfoLngLat(JobInfo jobInfo) {
        if(Strings.isNullOrEmpty(jobInfo.getWorkAddress())) return;
        try{
            LngLat lngLat = GaodeUtils.getLagLat(jobInfo.getWorkAddress());
            jobInfo.setLng(lngLat.getLng()).setLat(lngLat.getLat());
        }catch (NullPointerException e) {
            log.warning(jobInfo.getRecruitTitle() + "地址:" + jobInfo.getWorkAddress() + "无法获取经纬度");
        }
    }

    private static String getUrl(String address) {
        return String.format(
                "https://restapi.amap.com/v3/geocode/geo?address=%s&city=%s&key=%s",
                address, CITY, KEY
        );
    }
}
